#include "main.h"
#include "mainframe.h"
#include "pm/manager.h"
#include <wx/fileconf.h>

IMPLEMENT_APP(App);


static const wxString KEY_LANG = wxT("lang");

// language data
static const wxLanguage langIds[] = {
    wxLANGUAGE_DEFAULT,
    wxLANGUAGE_FRENCH,
    wxLANGUAGE_ENGLISH
};

const wxString langNames[] = {
    wxT("System default"),
    wxT("French"),
    wxT("English")
};

wxCOMPILE_TIME_ASSERT( WXSIZEOF(langNames) == WXSIZEOF(langIds), LangArraysMismatch );



bool App::OnInit()
{
	wxConfigBase::Set( new wxFileConfig(wxT("ProjectManager"), wxEmptyString, wxT(".projectmgr"), wxEmptyString, wxCONFIG_USE_LOCAL_FILE) );

	// Manage i18n
	long lang = wxNOT_FOUND;
	if (wxConfigBase::Get()->Read(KEY_LANG, &lang) == false) {
		lang = wxGetSingleChoiceIndex(wxT("Please choose language:"), wxT("Language"), WXSIZEOF(langNames), langNames);
		lang = langIds[lang];
	}	
    if (lang != wxNOT_FOUND) {
        if (!m_locale.Init(lang, wxLOCALE_CONV_ENCODING)) {
            wxLogError(wxT("This language is not supported by the system."));
            return false;
        }
		wxConfigBase::Get()->Write(KEY_LANG, lang);
    }
    wxLocale::AddCatalogLookupPathPrefix(wxT("lang"));
    m_locale.AddCatalog(wxT("pm"));
#ifdef __LINUX__
    {
        wxLogNull noLog;
        m_locale.AddCatalog(wxT("fileutils"));
    }
#endif

	// Create a database into memory
	pm::load(pm::Manager::MEMORY);
	
	MainFrame* mainFrame = new MainFrame( NULL );
	SetTopWindow(mainFrame);
	mainFrame->Show();
	
	if (argc > 1) {
		mainFrame->OpenFile(argv[1]);
	}
	return true;
}

int App::OnExit()
{
	delete wxConfigBase::Set(NULL);
	return wxApp::OnExit();
}

int App::GetActiveProject() const
{
	return dynamic_cast<MainFrame*>(GetTopWindow())->GetActiveProject();
}
